from celery import current_app
from flask import Blueprint, jsonify, send_file, request, abort, make_response, redirect, url_for
from datetime import date, datetime, timedelta
import io
import pandas as pd
import zipfile
from .models import ScheduleResult, Elderdemand, TimeSlot, DicNursingAction, Attendantskills, CaregiverSchedule, db
from .scheduler import Plan
from config_params import params
from sqlalchemy import func
from .redis_utils import get_redis_connection
from .redis_utils import get_update_time
import calendar
import copy
from uuid import uuid4

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return "Welcome to the Nursing Schedule App!"

@main.route('/check_update', methods=['GET'])
def check_update():
    redis_conn = get_redis_connection()
    if redis_conn:
        update_value = redis_conn.get(current_app.config['REDIS_UPDATE_KEY'])
        return jsonify({"update": update_value})
    else:
        return jsonify({"error": "无法连接到Redis"}), 500

@main.route('/last_update_time', methods=['GET'])
def get_last_update_time():
    last_update_time = get_update_time()
    if last_update_time:
        return jsonify({"last_update_time": last_update_time})
    else:
        return jsonify({"error": "无法获取最后更新时间"}), 404

@main.route('/generate_and_save_schedule', methods=['GET', 'POST'])
def generate_and_save_schedule():
    plan = Plan(params)
    client_schedules = plan.run()

    if request.method == 'POST':
        return jsonify({"message": "Schedules generated and saved successfully", "date": datetime.now().isoformat()})
    else:
        return redirect(url_for('main.view_schedule'))

@main.route('/caregiver_schedule/<string:caregiver_id>', methods=['GET'])
def get_caregiver_schedule(caregiver_id):
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()

    schedules = CaregiverSchedule.query.filter(
        CaregiverSchedule.caregiver_id == caregiver_id,
        func.date(CaregiverSchedule.schedule_date) == schedule_date
    ).order_by(CaregiverSchedule.time_slot).all()

    return jsonify([{
        'time_slot': schedule.time_slot,
        'is_available': schedule.is_available
    } for schedule in schedules])

@main.route('/update_caregiver_availability', methods=['POST'])
def update_caregiver_availability():
    data = request.json
    caregiver_id = data.get('caregiver_id')
    schedule_date_str = data.get('date')
    time_slot = data.get('time_slot')
    is_available = data.get('is_available')

    if not all([caregiver_id, schedule_date_str, time_slot is not None, is_available is not None]):
        return jsonify({'error': 'Missing required data'}), 400

    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()

    schedule = CaregiverSchedule.query.filter_by(
        caregiver_id=caregiver_id,
        schedule_date=schedule_date,
        time_slot=time_slot
    ).first()

    if schedule:
        schedule.is_available = is_available
    else:
        new_schedule = CaregiverSchedule(
            caregiver_id=caregiver_id,
            schedule_date=schedule_date,
            time_slot=time_slot,
            is_available=is_available
        )
        db.session.add(new_schedule)

    try:
        db.session.commit()
        return jsonify({'message': 'Caregiver availability updated successfully'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@main.route('/view_schedule', methods=['GET'])
def view_schedule():
    elder = request.args.get('elder')
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()

    def process_time_slot(ts):
        return {
            'id': ts.id,
            'elder': ts.elder,
            'time_slot': ts.time_slot,
            'activity': ts.activity,
            'activity_id': ts.activity_id,
            'caregiver': 'lack' if ts.caregiver_id == '-1' else ts.caregiver,
            'caregiver_id': ts.caregiver_id,
            'schedule_date': ts.schedule_date.isoformat()
        }

    try:
        if elder:
            schedule_result = ScheduleResult.query.filter(
                ScheduleResult.elder == elder,
                db.func.date(ScheduleResult.schedule_date) == schedule_date
            ).first()
            if schedule_result:
                time_slots = TimeSlot.query.filter_by(schedule_result_id=schedule_result.id).order_by(
                    TimeSlot.time_order).all()
                return jsonify({
                    'elder': elder,
                    'schedule_date': schedule_date.isoformat(),
                    'json_data': schedule_result.schedule_data,
                    'time_slots': [process_time_slot(ts) for ts in time_slots]
                })
            else:
                return jsonify({'error': 'Schedule not found'}), 404
        else:
            all_schedules = ScheduleResult.query.filter(db.func.date(ScheduleResult.schedule_date) == schedule_date).all()
            grouped_schedules = {}
            for sr in all_schedules:
                elder = sr.elder
                time_slots = TimeSlot.query.filter_by(schedule_result_id=sr.id).order_by(TimeSlot.time_order).all()
                grouped_schedules[elder] = {
                    'schedule_date': sr.schedule_date.isoformat(),
                    'json_data': sr.schedule_data,
                    'time_slots': [process_time_slot(ts) for ts in time_slots]
                }
            return jsonify(grouped_schedules)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main.route('/download_schedule/<string:elder>', methods=['GET'])
def download_schedule(elder):
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()

    schedule_result = ScheduleResult.query.filter(
        ScheduleResult.elder == elder,
        func.date(ScheduleResult.schedule_date) == schedule_date
    ).first()

    if not schedule_result:
        abort(404, description="Schedule not found")

    time_slots = TimeSlot.query.filter_by(schedule_result_id=schedule_result.id).order_by(TimeSlot.time_order).all()

    df = pd.DataFrame([(ts.time_slot, ts.elder, ts.activity, ts.activity_id, 'lack' if ts.caregiver_id == '-1' else ts.caregiver, ts.caregiver_id, ts.schedule_date) for ts in time_slots],
                      columns=['TimeSlot', 'Elder', 'Activity', 'ActivityId', 'Caregiver', 'CaregiverId', 'ScheduleDate'])

    excel_buffer = io.BytesIO()
    df.to_excel(excel_buffer, index=False)
    excel_buffer.seek(0)

    return send_file(
        excel_buffer,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        download_name=f'{elder}_schedule_{schedule_date.isoformat()}.xlsx'
    )

@main.route('/download_all_schedules', methods=['GET'])
def download_all_schedules():
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()
    schedule_results = ScheduleResult.query.filter(db.func.date(ScheduleResult.schedule_date) == schedule_date).all()

    if not schedule_results:
        abort(404, description="No schedules found for the specified date")

    memory_file = io.BytesIO()
    with zipfile.ZipFile(memory_file, 'w') as zf:
        for schedule_result in schedule_results:
            time_slots = TimeSlot.query.filter_by(schedule_result_id=schedule_result.id).order_by(TimeSlot.time_order).all()
            df = pd.DataFrame([(ts.time_slot, ts.activity, 'lack' if ts.caregiver_id == '-1' else ts.caregiver) for ts in time_slots],
                              columns=['TimeSlot', 'Activity', 'Caregiver'])
            excel_buffer = io.BytesIO()
            df.to_excel(excel_buffer, index=False)
            excel_buffer.seek(0)
            zf.writestr(f"{schedule_result.elder}_schedule.xlsx", excel_buffer.getvalue())

    memory_file.seek(0)

    return send_file(
        memory_file,
        mimetype='application/zip',
        as_attachment=True,
        download_name=f'all_schedules_{schedule_date.isoformat()}.zip'
    )

@main.route('/nursing_actions', methods=['GET'])
def get_nursing_actions():
    actions = DicNursingAction.query.all()
    return jsonify([{
        'id': action.id,
        'pid': action.pid,
        'name': action.name,
        'level': action.level,
        'nursing_level': action.nursing_level
    } for action in actions])

@main.route('/elders', methods=['GET'])
def get_elders():
    elders = Elderdemand.query.filter_by(arrange='1').all()  # 只返回arrange为'1'的老人
    return jsonify([{
        'id': elder.id,
        'elder': elder.elder,
        'actions': elder.actions,
        'arrange': elder.arrange
    } for elder in elders])

@main.route('/caregivers', methods=['GET'])
def get_caregivers():
    caregivers = Attendantskills.query.all()
    return jsonify([{
        'id': caregiver.id,
        'attendant_name': caregiver.attendant_name,
        'skills': caregiver.skills
    } for caregiver in caregivers])

@main.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': str(error)}), 404)

def init_app(app):
    app.register_blueprint(main)

    # 通过POST请求到 /generate_and_save_schedule  生成新的调度并保存到数据库。
    # 通过GET请求到 /view_schedule查看保存的调度。
    # 通过GET请求到 /download_all_schedules或 /download_schedule/<elder_id> 下载保存的调度。

    # 照护计划id
    # 老人id
    # 时间段
    # 护理动作
    # 护理员
    # 更新时间

# 三班制排班接口
@main.route('/generate_three_shift_schedule', methods=['GET', 'POST'])
def generate_three_shift_schedule():
    # 获取排班参数
    start_date_str = request.args.get('start_date', date.today().isoformat())
    start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date()
    
    schedule_type = request.args.get('schedule_type', params['schedule_type'])
    schedule_days = int(request.args.get('schedule_days', params['schedule_days']))
    
    # 根据排班类型计算需要排班的天数
    days_to_schedule = calculate_schedule_days(schedule_type, start_date, schedule_days)
    
    # 保存原始参数
    original_params = copy.deepcopy(params)
    
    # 设置三班制开始时间
    shift_start_time = request.args.get('shift_start_time', params['shift_start_time'])
    hours, minutes = map(int, shift_start_time.split(':'))
    shift_start_time_hours = hours + minutes/60
    
    # 设置白天/夜班权重
    day_night_weight = float(request.args.get('day_night_weight', params['day_night_weight']))
    
    results = []
    
    try:
        # 逐天进行排班
        for day_offset in range(days_to_schedule):
            current_date = start_date + timedelta(days=day_offset)
            
            # 运行原始排班算法
            plan = Plan(params)
            client_schedules = plan.run()
            
            # 将结果转换为三班制
            shift_schedules = convert_to_three_shifts(client_schedules, current_date, shift_start_time_hours, day_night_weight)
            
            # 保存三班制排班结果
            results.append(save_three_shift_schedule(shift_schedules, current_date))
        
        if request.method == 'POST':
            return jsonify({
                "message": "三班制排班已成功生成并保存", 
                "date": start_date.isoformat(),
                "days": days_to_schedule,
                "schedule_type": schedule_type
            })
        else:
            return redirect(url_for('main.view_three_shift_schedule'))
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 计算需要排班的天数
def calculate_schedule_days(schedule_type, start_date, schedule_days=1):
    if schedule_type == 'day':
        return schedule_days
    elif schedule_type == 'week':
        return 7
    elif schedule_type == 'month':
        year, month = start_date.year, start_date.month
        _, days_in_month = calendar.monthrange(year, month)
        return days_in_month
    elif schedule_type == 'quarter':
        # 计算季度天数
        quarter_start_month = ((start_date.month - 1) // 3) * 3 + 1
        days = 0
        for month_offset in range(3):
            month = quarter_start_month + month_offset
            year = start_date.year
            if month > 12:
                month -= 12
                year += 1
            _, days_in_month = calendar.monthrange(year, month)
            days += days_in_month
        return days
    elif schedule_type == 'year':
        year = start_date.year
        return 366 if calendar.isleap(year) else 365
    else:
        return schedule_days

# 将原始排班转换为三班制
def convert_to_three_shifts(client_schedules, schedule_date, shift_start_time_hours, day_night_weight):
    shift_schedules = []
    
    # 定义三个班次
    shifts = [
        {"name": "早班", "start": shift_start_time_hours, "end": shift_start_time_hours + 8},
        {"name": "中班", "start": shift_start_time_hours + 8, "end": shift_start_time_hours + 16},
        {"name": "晚班", "start": shift_start_time_hours + 16, "end": shift_start_time_hours + 24},
    ]
    
    # 标准化班次时间，处理跨天情况
    for shift in shifts:
        shift["start"] = shift["start"] % 24
        shift["end"] = shift["end"] % 24
        # 跨天处理
        if shift["end"] < shift["start"]:
            shift["cross_day"] = True
        else:
            shift["cross_day"] = False
    
    # 遍历每个客户的排班
    for elder, schedule in client_schedules.items():
        for time_slot in schedule["time_slots"]:
            slot_time = time_slot["time_slot"]
            
            # 解析时间槽
            start_time_str, end_time_str = slot_time.split('-')
            start_hour, start_minute = map(int, start_time_str.split(':'))
            end_hour, end_minute = map(int, end_time_str.split(':'))
            
            slot_start_time = start_hour + start_minute/60
            slot_end_time = end_hour + end_minute/60
            
            # 确定时间槽属于哪个班次
            for shift_index, shift in enumerate(shifts):
                # 处理跨天情况
                if shift["cross_day"]:
                    # 如果班次跨天，需要特殊处理时间比较
                    if (slot_start_time >= shift["start"]) or (slot_start_time < shift["end"]):
                        # 确定正确的日期，如果时间在第二天，则日期+1
                        slot_date = schedule_date
                        if slot_start_time < shift["end"] and shift["start"] > shift["end"]:
                            slot_date = schedule_date + timedelta(days=1)
                        
                        # 创建三班制排班项
                        shift_schedule = {
                            "elder": elder,
                            "time_slot": slot_time,
                            "activity": time_slot["activity"],
                            "activity_id": time_slot["activity_id"],
                            "caregiver": time_slot["caregiver"],
                            "caregiver_id": time_slot["caregiver_id"],
                            "shift": shift_index,  # 0=早班, 1=中班, 2=晚班
                            "shift_name": shift["name"],
                            "schedule_date": slot_date
                        }
                        shift_schedules.append(shift_schedule)
                        break
                else:
                    # 非跨天班次的处理
                    if shift["start"] <= slot_start_time < shift["end"]:
                        shift_schedule = {
                            "elder": elder,
                            "time_slot": slot_time,
                            "activity": time_slot["activity"],
                            "activity_id": time_slot["activity_id"],
                            "caregiver": time_slot["caregiver"],
                            "caregiver_id": time_slot["caregiver_id"],
                            "shift": shift_index,  # 0=早班, 1=中班, 2=晚班
                            "shift_name": shift["name"],
                            "schedule_date": schedule_date
                        }
                        shift_schedules.append(shift_schedule)
                        break
    
    return shift_schedules

# 保存三班制排班结果
def save_three_shift_schedule(shift_schedules, schedule_date):
    results = {}
    
    try:
        # 按老人分组保存
        for schedule in shift_schedules:
            elder = schedule["elder"]
            schedule_date = schedule["schedule_date"]
            
            # 为每位老人创建ScheduleResult记录
            if elder not in results:
                schedule_result = ScheduleResult.query.filter_by(
                    elder=elder, 
                    schedule_date=schedule_date
                ).first()
                
                if not schedule_result:
                    schedule_result = ScheduleResult(
                        id=str(uuid4()),
                        elder=elder,
                        schedule_date=schedule_date,
                        schedule_data={"shift_schedule": True}
                    )
                    db.session.add(schedule_result)
                    db.session.flush()
                
                results[elder] = {
                    "schedule_result": schedule_result,
                    "time_slots": []
                }
            
            # 创建时间槽记录
            time_slot = TimeSlot(
                id=str(uuid4()),
                schedule_result_id=results[elder]["schedule_result"].id,
                elder=elder,
                time_slot=schedule["time_slot"],
                activity=schedule["activity"],
                activity_id=schedule["activity_id"],
                caregiver=schedule["caregiver"],
                caregiver_id=schedule["caregiver_id"],
                time_order=len(results[elder]["time_slots"]),
                schedule_date=schedule_date
            )
            
            db.session.add(time_slot)
            results[elder]["time_slots"].append(time_slot)
        
        db.session.commit()
        return {"success": True, "date": schedule_date.isoformat()}
    
    except Exception as e:
        db.session.rollback()
        raise e

# 查看三班制排班结果
@main.route('/view_three_shift_schedule', methods=['GET'])
def view_three_shift_schedule():
    elder = request.args.get('elder')
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()
    
    try:
        if elder:
            # 查询特定老人的排班
            schedule_result = ScheduleResult.query.filter(
                ScheduleResult.elder == elder,
                func.date(ScheduleResult.schedule_date) == schedule_date
            ).first()
            
            if schedule_result:
                time_slots = TimeSlot.query.filter_by(schedule_result_id=schedule_result.id).order_by(TimeSlot.time_order).all()
                
                # 将时间槽按班次分组
                shifts = {"早班": [], "中班": [], "晚班": []}
                
                for ts in time_slots:
                    # 解析时间槽确定班次
                    shift_name = determine_shift(ts.time_slot, params['shift_start_time'])
                    
                    slot_data = {
                        'id': ts.id,
                        'elder': ts.elder,
                        'time_slot': ts.time_slot,
                        'activity': ts.activity,
                        'activity_id': ts.activity_id,
                        'caregiver': 'lack' if ts.caregiver_id == '-1' else ts.caregiver,
                        'caregiver_id': ts.caregiver_id,
                        'schedule_date': ts.schedule_date.isoformat()
                    }
                    
                    if shift_name in shifts:
                        shifts[shift_name].append(slot_data)
                
                return jsonify({
                    'elder': elder,
                    'schedule_date': schedule_date.isoformat(),
                    'shifts': shifts
                })
            else:
                return jsonify({'error': '未找到排班结果'}), 404
        else:
            # 查询所有老人的排班
            all_schedules = ScheduleResult.query.filter(
                func.date(ScheduleResult.schedule_date) == schedule_date
            ).all()
            
            grouped_schedules = {}
            
            for sr in all_schedules:
                elder = sr.elder
                time_slots = TimeSlot.query.filter_by(schedule_result_id=sr.id).order_by(TimeSlot.time_order).all()
                
                if elder not in grouped_schedules:
                    grouped_schedules[elder] = {
                        'schedule_date': sr.schedule_date.isoformat(),
                        'shifts': {"早班": [], "中班": [], "晚班": []}
                    }
                
                for ts in time_slots:
                    shift_name = determine_shift(ts.time_slot, params['shift_start_time'])
                    
                    slot_data = {
                        'id': ts.id,
                        'elder': ts.elder,
                        'time_slot': ts.time_slot,
                        'activity': ts.activity,
                        'activity_id': ts.activity_id,
                        'caregiver': 'lack' if ts.caregiver_id == '-1' else ts.caregiver,
                        'caregiver_id': ts.caregiver_id,
                        'schedule_date': ts.schedule_date.isoformat()
                    }
                    
                    if shift_name in grouped_schedules[elder]['shifts']:
                        grouped_schedules[elder]['shifts'][shift_name].append(slot_data)
            
            return jsonify(grouped_schedules)
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 确定时间槽属于哪个班次
def determine_shift(time_slot, shift_start_time):
    start_time_str, _ = time_slot.split('-')
    start_hour, start_minute = map(int, start_time_str.split(':'))
    
    # 将开始时间转换为小时
    slot_time = start_hour + start_minute/60
    
    # 获取班次开始时间
    start_hour, start_minute = map(int, shift_start_time.split(':'))
    shift_start = start_hour + start_minute/60
    
    # 计算各班次的时间范围
    early_shift_start = shift_start
    early_shift_end = (early_shift_start + 8) % 24
    
    mid_shift_start = (early_shift_start + 8) % 24
    mid_shift_end = (mid_shift_start + 8) % 24
    
    night_shift_start = (mid_shift_start + 8) % 24
    night_shift_end = (night_shift_start + 8) % 24
    
    # 处理跨天班次
    if early_shift_end < early_shift_start:
        if slot_time >= early_shift_start or slot_time < early_shift_end:
            return "早班"
    elif early_shift_start <= slot_time < early_shift_end:
        return "早班"
    
    if mid_shift_end < mid_shift_start:
        if slot_time >= mid_shift_start or slot_time < mid_shift_end:
            return "中班"
    elif mid_shift_start <= slot_time < mid_shift_end:
        return "中班"
    
    return "晚班"  # 默认为晚班

# 下载三班制排班结果
@main.route('/download_three_shift_schedule/<string:elder>', methods=['GET'])
def download_three_shift_schedule(elder):
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()
    
    schedule_result = ScheduleResult.query.filter(
        ScheduleResult.elder == elder,
        func.date(ScheduleResult.schedule_date) == schedule_date
    ).first()
    
    if not schedule_result:
        abort(404, description="未找到排班结果")
    
    time_slots = TimeSlot.query.filter_by(schedule_result_id=schedule_result.id).order_by(TimeSlot.time_order).all()
    
    # 将时间槽按班次分组
    shifts_data = []
    
    for ts in time_slots:
        shift_name = determine_shift(ts.time_slot, params['shift_start_time'])
        
        shifts_data.append({
            'TimeSlot': ts.time_slot,
            'Elder': ts.elder,
            'Activity': ts.activity,
            'ActivityId': ts.activity_id,
            'Caregiver': 'lack' if ts.caregiver_id == '-1' else ts.caregiver,
            'CaregiverId': ts.caregiver_id,
            'ScheduleDate': ts.schedule_date,
            'Shift': shift_name
        })
    
    df = pd.DataFrame(shifts_data)
    
    excel_buffer = io.BytesIO()
    df.to_excel(excel_buffer, index=False)
    excel_buffer.seek(0)
    
    return send_file(
        excel_buffer,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        download_name=f'{elder}_three_shift_schedule_{schedule_date.isoformat()}.xlsx'
    )

# 添加老人参与排班控制接口
@main.route('/update_elder_participation', methods=['POST'])
def update_elder_participation():
    data = request.json
    elder_id = data.get('elder_id')
    participate = data.get('participate', '1')  # 默认参与排班
    
    if not elder_id:
        return jsonify({'error': '缺少老人ID'}), 400
    
    try:
        # 查找老人
        elder = Elderdemand.query.filter_by(id=elder_id).first()
        
        if not elder:
            return jsonify({'error': '未找到老人'}), 404
        
        # 更新老人的arrange字段
        elder.arrange = '1' if participate else '0'
        db.session.commit()
        
        return jsonify({
            'message': '老人排班参与状态已更新',
            'elder_id': elder_id,
            'participate': participate
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 查询参与排班的老人
@main.route('/participating_elders', methods=['GET'])
def get_participating_elders():
    try:
        elders = Elderdemand.query.filter_by(arrange='1').all()
        
        return jsonify([{
            'id': elder.id,
            'elder': elder.elder,
            'actions': elder.actions
        } for elder in elders])
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 新增老人接口
@main.route('/add_elder', methods=['POST'])
def add_elder():
    data = request.json
    elder_name = data.get('elder_name')
    actions = data.get('actions', '')
    arrange = data.get('arrange', '1')  # 默认参与排班
    
    if not elder_name:
        return jsonify({'error': '缺少老人姓名'}), 400
    
    try:
        # 检查老人是否已存在
        existing_elder = Elderdemand.query.filter_by(elder=elder_name).first()
        
        if existing_elder:
            return jsonify({'error': '老人已存在'}), 400
        
        # 创建新老人记录
        new_elder = Elderdemand(
            elder=elder_name,
            actions=actions,
            arrange=arrange
        )
        db.session.add(new_elder)
        db.session.commit()
        
        return jsonify({
            'message': '老人添加成功',
            'id': new_elder.id,
            'elder': new_elder.elder,
            'actions': new_elder.actions,
            'arrange': new_elder.arrange
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 更新老人照护需求
@main.route('/update_elder_care_needs', methods=['POST'])
def update_elder_care_needs():
    data = request.json
    elder_id = data.get('elder_id')
    actions = data.get('actions')
    
    if not elder_id or actions is None:
        return jsonify({'error': '缺少必要参数'}), 400
    
    try:
        # 查找老人
        elder = Elderdemand.query.filter_by(id=elder_id).first()
        
        if not elder:
            return jsonify({'error': '未找到老人'}), 404
        
        # 更新老人的照护需求
        elder.actions = actions
        db.session.commit()
        
        return jsonify({
            'message': '老人照护需求已更新',
            'elder_id': elder_id,
            'actions': actions
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 批量设置老人参与排班状态
@main.route('/batch_update_elder_participation', methods=['POST'])
def batch_update_elder_participation():
    data = request.json
    elder_ids = data.get('elder_ids', [])
    participate = data.get('participate', '1')  # 默认参与排班
    
    if not elder_ids:
        return jsonify({'error': '未提供老人ID列表'}), 400
    
    try:
        # 查找老人并批量更新
        updated_elders = []
        for elder_id in elder_ids:
            elder = Elderdemand.query.filter_by(id=elder_id).first()
            if elder:
                elder.arrange = '1' if participate else '0'
                updated_elders.append({
                    'id': elder.id,
                    'elder': elder.elder,
                    'participate': participate
                })
        
        db.session.commit()
        
        return jsonify({
            'message': f'已更新{len(updated_elders)}位老人的排班参与状态',
            'updated_elders': updated_elders
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 获取已排班老人列表
@main.route('/scheduled_elders', methods=['GET'])
def get_scheduled_elders():
    schedule_date_str = request.args.get('date', date.today().isoformat())
    schedule_date = datetime.strptime(schedule_date_str, "%Y-%m-%d").date()
    
    try:
        # 查询指定日期有排班结果的老人
        schedule_results = ScheduleResult.query.filter(
            func.date(ScheduleResult.schedule_date) == schedule_date
        ).all()
        
        scheduled_elders = [{'id': sr.elder, 'schedule_date': sr.schedule_date.isoformat()} for sr in schedule_results]
        
        return jsonify(scheduled_elders)
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500
